import React from 'react';
import { TreeSelect, message } from 'antd';
import { getOrganizationTree } from '@/services/Organization/orgmanage';

const filterTree = (tree, str = '') =>
    tree.map(({ children, organizationName, organizationCode, ...props }) => {
        const path = `${str}${str ? '/' : ''}${organizationName}`;
        if (children && children.length > 0) {
            return {
                children: filterTree(children, path),
                title: organizationName,
                value: organizationCode,
                key: organizationCode,
                path,
                ...props
            };
        }
        return {
            children: '',
            title: organizationName,
            value: organizationCode,
            key: organizationCode,
            path,
            ...props
        };
    });

const OrganizationTreeSelect = (props, ref) => {
    const [treeData, setTreeData] = React.useState([]);
    const fetchTree = async () => {
        const res = await getOrganizationTree({ showTreeFlag: 1 });
        const { code, data, msg } = res;
        if (code === 10000) {
            setTreeData(filterTree(data));
        } else {
            message.error(msg);
        }
    };

    React.useEffect(() => {
        fetchTree();
    }, []);

    return (
        <TreeSelect
            ref={ref}
            style={{ width: '100%', maxWidth: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={treeData}
            placeholder="请选择组织机构"
            treeDefaultExpandAll
            showSearch
            treeNodeFilterProp="title"
            treeNodeLabelProp="path"
            allowClear
            {...props}
        />
    );
};

export default React.forwardRef(OrganizationTreeSelect);
